const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');

const app = express();
const port = 3000;

// 中间件配置
app.use(cors());  // 允许跨域请求
app.use(express.json());  // 解析 JSON 请求体

// 创建数据库连接池
const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'ruins',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 将连接池转换为 Promise 形式
const promisePool = pool.promise();
// 分类映射配置
const CATEGORY_MAP = {
    opera: '传统戏曲',
    handicraft: '手工艺',
    music:"音乐",
    dance:"舞蹈"
  };
// 获取所有非遗项目
// 戏曲
app.get('/:category/heritage_projects', async (req, res) => {
    try {
        const category = CATEGORY_MAP[req.params.category]
        const [rows] = await promisePool.query('SELECT * FROM heritage_projects WHERE category=?',[category]);
        res.json(rows);
    } catch (err) {
        res.status(500).json({ error: '查询失败', details: err.message });
    }
});
// 删除一个
app.delete('/:category/heritage_projects/:id',async (req,res)=>{
    const id=req.params.id
    const category=CATEGORY_MAP[req.params.category]
    try{
        await promisePool.query( 'DELETE FROM heritage_projects WHERE id = ? AND category = ?',
            [id, category]);
        res.json({ message: '删除成功' });
    }catch (err) {
        res.status(500).json({ error: '删除失败', details: err.message });
    }
})
// 编辑
app.post('/:category/heritage_projects', async (req, res) => {
    try {
        const formData = req.body;
        const category=CATEGORY_MAP[req.params.category]
        const sql = `INSERT INTO heritage_projects (project_name, category, sub_category, description, origin, characteristics, representative_artists, representative_method, popular_regions, related_festivals, protection_level, protection_unit, related_documents, multimedia_resources, record_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
        const data = [
            formData.project_name,
            formData.category,
            formData.sub_category,
            formData.description,
            formData.origin,
            formData.characteristics,
            formData.representative_artists,
            formData.representative_method,
            formData.popular_regions,
            formData.related_festivals,
            formData.protection_level,
            formData.protection_unit,
            formData.related_documents,
            formData.multimedia_resources,
            formData.record_date
        ];

        const [result] = await promisePool.query(sql, data);
        res.json({ message: '添加成功', id: result.insertId });
    } catch (err) {
        console.error('添加错误:', err);
        res.status(500).json({ error: '添加失败', details: err.message });
    }
});
// 更新非遗项目
app.put('/:category/heritage_projects/:id', async (req, res) => {
    try {
        // 获取 id 并转换为数字
        const id = parseInt(req.params.id, 10);
        // 获取分类
        const category = CATEGORY_MAP[req.params.category];
        // 获取请求体数据
        const data = req.body;
        // 构造 SQL 查询
        const sql = `
            UPDATE heritage_projects 
            SET 
                project_name = ?,
                category = ?,
                sub_category = ?,
                description = ?,
                origin = ?,
                characteristics = ?,
                representative_artists = ?,
                representative_method = ?,
                popular_regions = ?,
                related_festivals = ?,
                protection_level = ?,
                protection_unit = ?
            WHERE id = ? AND category = ?
        `;
        // 构造参数数组
        const params = [
            data.project_name,
            category,
            data.sub_category,
            data.description,
            data.origin,
            data.characteristics,
            data.representative_artists,
            data.representative_method,
            data.popular_regions,
            data.related_festivals,
            data.protection_level,
            data.protection_unit,
            id,
            category
        ];
        // 执行更新操作
        const [result] = await promisePool.query(sql, params);
        // 检查是否更新成功
        if (result.affectedRows > 0) {
            res.json({ message: '更新成功' });
        } else {
            res.status(404).json({ error: '未找到要更新的项目' });
        }
    } catch (err) {
        // 打印错误详情
        console.error('更新错误:', err);
        res.status(500).json({ error: '更新失败', details: err.message });
    }
});
// 传承人
// 获取数据
app.get("/artist/heritage_artists",async (req,res)=>{
    try{
        const [row]=await promisePool.query("select * from heritage_artists")
        res.json(row)
    }catch(err){
        res.status(500).json({ error: '查询失败', details: err.message });
    }
})
// 

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});

// 处理未捕获的异常
process.on('unhandledRejection', (err) => {
    console.error('未捕获的 Promise 异常：', err);
});
